﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Runtime.Serialization;
using System.Data;
using System.Data.OracleClient;
//using java.io;
//using java.util.zip;
using System.Net;
using System.IO;
using System.Web.Hosting;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.ComponentModel;
using VAdvantage.Logging;
using VAdvantage.DataBase;
using VAdvantage.MailBox;
using System.Globalization;
using System.Runtime.CompilerServices;
using Google.GData.Client;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Extensions;
using VAdvantageSvc.Classes;



namespace VAdvantageSvc
{
    [ServiceContract(Namespace = "VAdvantageSvc")]
    public interface IDataServicesBasic
    {
        [OperationContract]
        String GetDataXMLPaging(string sql, int start, int end, bool? state, string tableName);

        [OperationContract] //Calender Data
        byte[] GetData(String tables, out CustomException serviceError);

        [OperationContract] //Calender Data
        string GetDataTables(String tables);

        //[OperationContract]
        //DataSetData GetDataObject(string sql, int pageNumber, int pageSize, out CustomException ServiceError);
        //[OperationContract]
        //String SetDataObject();

        [OperationContract]
        String GetDataXML(string sql, out CustomException ServiceError);

        [OperationContract]
        String GetTopicInfo(String url, bool isInitConfig, string langCode, string searchText, string option, out string serviceError);

        [OperationContract]
        String GetInstruction(int K_TopicInfo_ID, string langCode, String optional, out String serviceError);




        [OperationContract]
        Byte[] Speak(string textToSay);

        [OperationContract]
        string UpdateLoginTime(int AD_Client_ID, String url, string loginTime);

        [OperationContract]
        int GetQuota(int AD_Client_ID, String url, string other);

        [OperationContract]
        Dictionary<string, long> GetAppSpace(List<string> pathOfDirectory);

        [OperationContract]
        String GetDataPaging(string sql, int start, int pageSize, out CustomException ServiceError);

        [OperationContract]
        List<ContactsInfo> ImportContacts(string username, string password, out string ErrorMsg);

        //[OperationContract]
        //Dictionary<string, string> ExportContacts(List<ContactsInfo> cinfo, string username, string password, out string errorMsg);

        [OperationContract]
        string GetWindowTabsFields(String AD_Window_ID, String AD_Role_ID, bool isBaseLanguage, string lang, out CustomException error);

        [OperationContract]
        VAdvantageSvc.DataContracts.AboutUs AboutUS();


    }


    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class DataServicesBasic : IDataServicesBasic
    {
        private string connectionString = System.Configuration.ConfigurationSettings.AppSettings["oracleConnectionString"];

        [MethodImpl(MethodImplOptions.Synchronized)]
        public string GetDataXMLPaging(string sql, int start, int end, bool? state, String tableName)
        {
            DataSet ds;
            OracleConnection Connection = new OracleConnection(connectionString);
            try
            {
                OracleDataAdapter adapter = new OracleDataAdapter();
                adapter.SelectCommand = new OracleCommand(sql);
                Connection.Open();
                adapter.SelectCommand.Connection = Connection;
                ds = new DataSet();
                adapter.Fill(ds, start, end - start, "Table");
                if (ds.Tables.Count > 1)
                {
                    DataTable data = ds.Tables[0];
                }
            }
            catch (Exception err)
            {
                VLogger.Get().Severe(err.Message);
                return null;
            }
            finally
            {
                Connection.Close();
            }

            StringBuilder xml = new StringBuilder("");
            StringBuilder schema = new StringBuilder("");



            if (state == null)
            {
                //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
                xml.Append(ds.GetXml());
                xml.Remove(0, 12);
                xml.Remove(xml.Length - 13, 13);
            }
            else if ((bool)state)
            {
                //schema.Append(ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>"));
                schema.Append("<TestDataSet>");
                xml.Append(ds.GetXml());
                xml.Remove(xml.Length - 13, 13);
                xml.Insert(0, schema.ToString());
            }
            else
            {
                xml.Append(ds.GetXml());
                xml.Remove(0, 12).Append("</TestDataSet>"); ;
            }

            return xml.ToString();
        }

        //public List<string> ExecuteMultipleQueries(List<string> sqlList, String trxName, out CustomException error)
        //{
        //    List<String> logs = new List<string>();
        //    error = null;
        //    try
        //    {
        //        foreach (String sql in sqlList)
        //        {
        //            try
        //            {
        //                VAdvantage.DataBase.DB.ExecuteQuery(sql, null, trxName);
        //            }
        //            catch (Exception e)
        //            {
        //                logs.Add(sql + "==>" + e.Message);
        //                error = new CustomException(e);
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        error = new CustomException(e);
        //    }
        //    return logs;
        //}

        //Calender Data
        public byte[] GetData(String tables, out CustomException serviceError)
        {
            // Create DataSet with connection string
            serviceError = null;
            byte[] result = null;
            try
            {
                var ds = GetDataSet();
                // Load data into DataSet

                ds.Fill(tables.Split('/'));

                // Persist to stream
                var ms = new System.IO.MemoryStream();
                ds.WriteXml(ms, XmlWriteMode.WriteSchema);
                result = ms.ToArray();
            }
            catch (Exception ex)
            {
                serviceError = new CustomException(ex);
                result = null;
            }

            // Return stream data
            return result;
        }

        SmartDataSet GetDataSet()
        {
            // Get physical location of the mdb file
            //string mdb = Path.Combine(
            //  Context.Request.PhysicalApplicationPath, @"App_Data\Schedule.mdb");

            //// Check that the file exists
            //if (!File.Exists(mdb))
            //{
            //    string msg = string.Format("Cannot find database file {0}.", mdb);
            //    throw new FileNotFoundException(msg);
            //}

            //// Make sure file is not read-only (source control often does this...)
            //FileAttributes att = File.GetAttributes(mdb);
            //if ((att & FileAttributes.ReadOnly) != 0)
            //{
            //    att &= ~FileAttributes.ReadOnly;
            //    File.SetAttributes(mdb, att);
            //}

            // Create and initialize the SmartDataSet
            var dataSet = new SmartDataSet();
            dataSet.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["oracleConnectionString"];

            // sample connection string for SQL Server Express (replace Initial Catalog value by the valid catalog name)
            // dataSet.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=.\\SQLEXPRESS";
            return dataSet;
        }

        public string GetDataXML(string sql, out CustomException error)
        {
            DataSet ds = null;
            try
            {
                ds = DB.ExecuteDataset(sql);// paramIn, trxName);
                //adapter.Fill(ds);//, 'Data');// (PageNumber - 1) * PageSize, PageSize, 'Data');
                //adapter.FillSchema(ds);//, SchemaType.Mapped, 'DataSchema');
                //if (PageSize > 0) // Reset Rowcount back to 0
                //{
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT 0 SET NO_BROWSETABLE OFF', (OracleCommand)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                if (ds.Tables.Count > 1)
                {
                    DataTable data = ds.Tables[0];
                    //DataTable schema = ds.Tables['DataSchema'];
                    // data.Merge(schema);
                    // ds.Tables.Remove(schema);
                }


                ds = Util.SetUtcDateTime(ds);

                //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
                error = null;
                //return schema + ds.GetXml() + " </TestDataSet>";

                StringWriter sw = new StringWriter();
                ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                return sw.ToString();
            }
            catch (Exception err)
            {
                error = new CustomException(err);
            }
            return "";
        }

        #region IDataServicesBasic Members

        public String GetDataTables(string tables)
        {
            // Create DataSet with connection string
            var ds = GetDataSet();
            // Load data into DataSet
            ds.Fill(tables.Split('/'));
            // Persist to stream
            //var ms = new System.IO.MemoryStream();
            //ds.WriteXml(ms, XmlWriteMode.WriteSchema);

            //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");

            // return schema + ds.GetXml() + " </TestDataSet>";


            StringWriter sw = new StringWriter();
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            return sw.ToString();


            //string str = ds.GetXml();
            //// Return stream data
            ////return ms.ToArray();
            //return str;
        }

        public String GetTopicInfo(String url, bool isInitConfig, string langCode, string searchText, string option, out string serviceError)
        {
            string path = HostingEnvironment.ApplicationPhysicalPath + "TopicInfo\\log.txt";



            var client = VAdvantageSvc.Classes.ServerEndPoint.GetOnLineHelpClient();
            string result = "";
            if (client != null)
            {
                try
                {
                    System.Net.ServicePointManager.Expect100Continue = false;
                    DataSet ds = client.GetTopicInfo(out serviceError, url, isInitConfig, langCode, searchText, option);
                    client.Close();

                    if (ds != null)
                    {
                        //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
                        //result = schema + ds.GetXml() + " </TestDataSet>";
                        StringWriter sw = new StringWriter();
                        ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                        result = sw.ToString();
                    }
                    else
                    {
                        serviceError = "Error Fetching record from server";
                    }
                }
                catch
                {
                    client.Close();
                    serviceError = "Error Fetching record from server";
                }
            }
            else
            {
                serviceError = "Service Point not found";
            }
            return result;
        }

        public String GetInstruction(int K_TopicInfo_ID, string langCode, String optional, out String serviceError)
        {
            var client = VAdvantageSvc.Classes.ServerEndPoint.GetOnLineHelpClient();
            string result = "";

            if (client != null)
            {
                try
                {
                    System.Net.ServicePointManager.Expect100Continue = false;
                    DataSet ds = client.GetInstruction(out serviceError, K_TopicInfo_ID, langCode, optional);
                    client.Close();

                    if (ds != null)
                    {
                        //string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
                        // result = schema + ds.GetXml() + " </TestDataSet>";
                        StringWriter sw = new StringWriter();
                        ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                        result = sw.ToString();
                    }
                    else
                    {
                        serviceError = "Error Fetching record from server";
                    }
                }
                catch
                {
                    serviceError = "Error Fetching record from server";
                    client.Close();
                }
            }
            else
            {
                serviceError = "Service Point Not found";
            }
            return result;
        }

        public Byte[] Speak(String textToSay)
        {
            Byte[] arr = null;


            //string url = string.Format("http://translate.google.com/translate_tts?tl={0}&q={1}","en", textToSay);
            //WebClient client = new WebClient();

            //arr = client.DownloadData(url);



            var client = VAdvantageSvc.Classes.ServerEndPoint.GetSpeechClient();
            System.Net.ServicePointManager.Expect100Continue = false;
            if (client != null)
            {
                arr = client.Speak(textToSay);
                client.Close();
            }
            //if (ret != null)
            //{
            //    //arr = Convert.FromBase64String(ret);
            //}
            return arr;
        }


        public string UpdateLoginTime(int AD_Client_ID, String url, string loginTime)
        {

            string retStr = "";


            var client = VAdvantageSvc.Classes.ServerEndPoint.GetCloudClient();

            object key = VAdvantage.Utility.SecureEngine.Encrypt(System.Configuration.ConfigurationSettings.AppSettings["accesskey"].ToString());

            if (client != null)
            {
                try
                {
                    System.Net.ServicePointManager.Expect100Continue = false;
                    retStr = client.SetLastLogin(AD_Client_ID, url, loginTime, key == null ? "key" : key.ToString());
                    client.Close();
                }
                catch
                {
                    client.Close();
                }
            }
            return retStr;
        }


        public int GetQuota(int AD_Client_ID, String url, string other)
        {
            //Use cloud or other source 
            return 30;
        }



        #endregion


        #region "AD_ WindoeTabFields"


        public string GetWindowTabsFields(String AD_Window_ID, String AD_Role_ID, bool isBaseLanguage, string lang, out CustomException error)
        {
            error = null;


            StringBuilder sqlWindow = new StringBuilder("");
            if (isBaseLanguage)
            {
                sqlWindow.Append("FROM AD_Window_v WHERE AD_Window_ID=" + AD_Window_ID.ToString());
                sqlWindow.Append(" AND AD_Role_ID=" + AD_Role_ID);
            }
            else
            {
                sqlWindow.Append("FROM AD_Window_vt w WHERE AD_Window_ID=" + AD_Window_ID.ToString());
                sqlWindow.Append(" AND AD_Role_ID=" + AD_Role_ID);
                sqlWindow.Append(" AND AD_Language='")
                .Append(lang).Append("'");
            }//1

            try
            {
                int AD_UserDef_Win_ID = VAdvantage.Utility.Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_UserDef_Win_ID " + sqlWindow.ToString()));
                sqlWindow.Insert(0, "SELECT * ");


                String sqlTab = "SELECT * FROM AD_Tab_v WHERE AD_Window_ID=" + AD_Window_ID;
                if (!isBaseLanguage)
                    sqlTab = "SELECT * FROM AD_Tab_vt WHERE AD_Window_ID=" + AD_Window_ID
                        + " AND AD_Language='" + lang + "'";
                if (AD_UserDef_Win_ID != 0)
                    sqlTab += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;
                sqlTab += " ORDER BY SeqNo"; //2


                String sqlFieldWhere = "SELECT AD_Tab_ID FROM AD_Tab_v WHERE AD_Window_ID=" + AD_Window_ID;
                if (!isBaseLanguage)
                    sqlFieldWhere = "SELECT AD_Tab_ID FROM AD_Tab_vt WHERE AD_Window_ID=" + AD_Window_ID
                        + " AND AD_Language='" + lang + "'";
                if (AD_UserDef_Win_ID != 0)
                    sqlFieldWhere += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;

                String sqlField = "SELECT * FROM AD_Field_v WHERE AD_Tab_ID IN ( " + sqlFieldWhere + " )";
                if (!isBaseLanguage)
                    sqlField = "SELECT * FROM AD_Field_vt WHERE AD_Tab_ID IN ( " + sqlFieldWhere + " )"
                        + " AND AD_Language='" + lang + "'";
                if (AD_UserDef_Win_ID != 0)
                    sqlField += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;
                sqlField += " ORDER BY IsDisplayed DESC, SeqNo"; //3


                var ds = GetDataSet();
                // Load data into DataSet
                ds.Fill(new string[] { sqlWindow.ToString(), sqlTab, sqlField });

                StringWriter sw = new StringWriter();
                ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                return sw.ToString();
            }
            catch (Exception e)
            {
                error = new CustomException(e);
            }
            return "";
        }

        #endregion



        public Dictionary<string, long> GetAppSpace(List<string> pathOfDirectory)
        {
            //long dirSize = 0;
            //FileInfo[] finfo = new  DirectoryInfo(pathOfDirectory).GetFiles( "*.*",SearchOption.AllDirectories);
            //foreach (FileInfo F1 in finfo)
            //{
            //    dirSize += F1.Length;
            //}
            //long finalSize = dirSize / (1024 * 1024);
            //return finalSize;
            long dirSize = 0;
            double finalSize = 0;
            //     List<string> values=new List<string>();
            string value = string.Empty;
            Dictionary<string, long> retValue = new Dictionary<string, long>();
            for (int i = 0; i < pathOfDirectory.Count; i++)
            {
                dirSize = 0;
                //value = (pathOfDirectory[i].Substring(pathOfDirectory[i].LastIndexOf(@"\"), pathOfDirectory[i].Length));
                value = (pathOfDirectory[i].Substring(pathOfDirectory[i].LastIndexOf(@"\") + 1, pathOfDirectory[i].Length - (pathOfDirectory[i].LastIndexOf(@"\") + 1)));
                if (Directory.Exists(pathOfDirectory[i]))
                {
                    FileInfo[] finfo = new DirectoryInfo(pathOfDirectory[i]).GetFiles("*.*", SearchOption.AllDirectories);
                    foreach (FileInfo F1 in finfo)
                    {
                        dirSize += F1.Length;
                    }
                    // finalSize = finalSize + dirSize;
                    finalSize = dirSize / (1024.00 * 1024);
                    finalSize = Math.Round(finalSize);
                    retValue.Add(value, Convert.ToInt64(finalSize));
                }
            }
            return retValue;
        }
        public String GetDataPaging(string sql, int start, int pageSize, out CustomException ServiceError)
        {

            DataSet ds = null; ;
            OracleConnection Connection = new OracleConnection(System.Configuration.ConfigurationSettings.AppSettings["oracleConnectionString"]);
            ServiceError = null;
            try
            {
                // Ctx ctx = new Ctx(ctxDic);
                //string clientName = "Log";
                //string storedPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "");
                //storedPath += clientName;

                OracleDataAdapter adapter = new OracleDataAdapter();

                adapter.SelectCommand = new OracleCommand(sql);
                Connection.Open();

                adapter.SelectCommand.Connection = Connection;
                //if (PageSize > 0)// Set rowcount =PageNumber * PageSize for best performance
                //{
                //    long RowCount = PageNumber * PageSize;
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT ' + RowCount.ToString() + ' SET NO_BROWSETABLE ON', (OracleConnection)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                ds = new DataSet();
                adapter.Fill(ds, start, pageSize, "Table");
                //adapter.FillSchema(ds);//, SchemaType.Mapped, 'DataSchema');
                //if (PageSize > 0) // Reset Rowcount back to 0
                //{
                //    OracleCommand cmd = new OracleCommand('SET ROWCOUNT 0 SET NO_BROWSETABLE OFF', (OracleCommand)Connection);
                //    cmd.ExecuteNonQuery();
                //}
                if (ds.Tables.Count > 1)
                {
                    DataTable data = ds.Tables[0];
                    //DataTable schema = ds.Tables['DataSchema'];
                    // data.Merge(schema);
                    // ds.Tables.Remove(schema);
                }
            }
            catch (Exception err)
            {
                ServiceError = new CustomException(err);
                return "";
            }
            finally
            {
                Connection.Close();
            }

            ds = Util.SetUtcDateTime(ds);

            // string schema = ds.GetXmlSchema().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<TestDataSet>");
            // error = null;

            //return schema + ds.GetXml() + " </TestDataSet>";

            StringWriter sw = new StringWriter();
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            return sw.ToString();



            // return "tested";

            //  return ds.GetXml();
        }
        public List<ContactsInfo> ImportContacts(string username, string password, out string errormsg)
        {
            List<ContactsInfo> contactinfo = new List<ContactsInfo>();
            try
            {
                RequestSettings rs = new RequestSettings("Vienna", username, password);
                rs.AutoPaging = true;
                ContactsRequest cr = new ContactsRequest(rs);
                Feed<Contact> f = cr.GetContacts();
                foreach (Contact e in f.Entries)
                {
                    ContactsInfo cinfo = new ContactsInfo();
                    cinfo.Title = e.Title;
                    cinfo.Content = e.Content;
                    cinfo.ID = e.Id;
                    cinfo.ContactName = e.Name.FullName;

                    if (e.ContactEntry.Birthday != null)
                    {
                        string[] date = e.ContactEntry.Birthday.Split('-');
                        DateTime datet = new DateTime(Convert.ToInt32(date.GetValue(0)), Convert.ToInt32(date.GetValue(1)), Convert.ToInt32(date.GetValue(2)));
                        cinfo.BirthDay = datet;
                    }
                    else
                    {
                        cinfo.BirthDay = null;
                    }

                    List<ContactPhone> contactPhone = new List<ContactPhone>();
                    foreach (Google.GData.Extensions.PhoneNumber PhoneNumber in e.Phonenumbers)
                    {
                        ContactPhone cphone = new ContactPhone();
                        if (PhoneNumber.Rel == ContactsRelationships.IsWork)
                        {
                            cphone.IsPhone = true;
                        }
                        else if (PhoneNumber.Rel == ContactsRelationships.IsMobile)
                        {
                            cphone.IsMobile = true;
                        }
                        else if (PhoneNumber.Rel == ContactsRelationships.IsHome)
                        {
                            cphone.IsPhone2 = true;
                        }
                        cphone.PhoneNumber = PhoneNumber.Value;
                        contactPhone.Add(cphone);
                    }
                    cinfo.PhoneNumber = contactPhone;

                    List<ContactAddressInfo> CAdd = new List<ContactAddressInfo>();
                    foreach (Google.GData.Extensions.StructuredPostalAddress pAdd in e.PostalAddresses)
                    {
                        ContactAddressInfo conAdd = new ContactAddressInfo();
                        if (pAdd.Rel != null)
                        {
                            if (pAdd.Rel == ContactsRelationships.IsHome)
                            {
                                conAdd.IsHomeAddress = true;
                            }
                            else if (pAdd.Rel == ContactsRelationships.IsWork)
                            {
                                conAdd.IsHomeAddress = false;

                            }
                            conAdd.City = pAdd.City;
                            conAdd.Country = pAdd.Country;
                            conAdd.Housename = pAdd.Housename;
                            conAdd.Region = pAdd.Region;
                            conAdd.StreetNo = pAdd.Street;
                            conAdd.Postcode = pAdd.Postcode;
                            CAdd.Add(conAdd);
                        }
                    }
                    cinfo.Address = CAdd;
                    foreach (Organization Organizations in e.Organizations)
                    {
                        cinfo.Organization = Organizations.Name;
                    }


                    List<ContactEmail> emailAdd = new List<ContactEmail>();
                    bool findWorkAddress = false;
                    List<string> allemails = new List<string>();

                    foreach (Google.GData.Extensions.EMail email in e.Emails)
                    {
                        allemails.Add(email.Address);
                        if (email.Rel == ContactsRelationships.IsWork && email.Primary == true)
                        {
                            findWorkAddress = true;
                            cinfo.EmailAddress = email.Address;
                        }
                        else if (email.Rel == ContactsRelationships.IsWork)
                        {
                            if (!findWorkAddress)
                            {
                                findWorkAddress = true;
                                cinfo.EmailAddress = email.Address;
                            }
                        }
                        else if (email.Primary)
                        {
                            if (!findWorkAddress)
                            {
                                cinfo.EmailAddress = email.Address;
                            }
                        }
                    }
                    cinfo.AllEmails = allemails;

                    //bool isEmailAdded = false;
                    //ContactEmail eAdd = new ContactEmail();
                    //string homeEmail = string.Empty;
                    //for (int j = 0; j < e.Emails.Count; j++)
                    //{
                    //    if (e.Emails[j].Rel.Contains("work"))
                    //    {
                    //       eAdd.Email = e.Emails[j].ToString();
                    //       isEmailAdded = true;
                    //        break;
                    //    }
                    //    if (e.Emails[j].Rel.Contains("other"))
                    //    {
                    //        homeEmail= e.Emails[j].ToString();
                    //        isEmailAdded = true;
                    //    }
                    //    if (e.Emails[j].Rel.Contains("home"))
                    //    {
                    //        homeEmail = e.Emails[j].ToString();
                    //        isEmailAdded = true;
                    //    }
                    //}
                    //if (!isEmailAdded)
                    //{
                    //    eAdd.Email = homeEmail;
                    //}
                    // cinfo.EmailAddress = emailAdd;


                    foreach (GroupMembership g in e.GroupMembership)
                    {
                        cinfo.Groupmembership = g.HRef;
                    }
                    foreach (IMAddress im in e.IMs)
                    {
                        cinfo.IMAddress = im.Address;
                    }
                    cinfo.IsCustomer = false;
                    cinfo.IsEmployee = false;
                    cinfo.IsVendor = false;
                    cinfo.IsSelected = false;
                    cinfo.Updated = e.Updated;
                    contactinfo.Add(cinfo);
                }
                errormsg = null;
            }
            catch (Exception ex)
            {
                errormsg = ex.Message.ToString();
            }
            return contactinfo;
        }
         
        public VAdvantageSvc.DataContracts.AboutUs AboutUS()
        {
            var client = VAdvantageSvc.Classes.ServerEndPoint.GetOnLineHelpClient();
            string key = VAdvantage.Utility.SecureEngine.Encrypt(System.Configuration.ConfigurationSettings.AppSettings["accesskey"].ToString());
            VAdvantageSvc.DataContracts.AboutUs ab = new DataContracts.AboutUs();

            if (client != null)
            {
                try
                {
                    System.Net.ServicePointManager.Expect100Continue = false;
                    CloudService.AboutUs about = client.Aboutvienna(key);
                    if (about.Logo != null)
                    {
                        ab.Logo = about.Logo;
                    }
                    if (about.Description != null)
                    {
                        ab.Description = about.Description;
                    }
                    if (about.Description1 != null)
                    {
                        ab.Description1 = about.Description1;
                    }
                    client.Close();
                }
                catch
                {
                    client.Close();
                    return null;
                }
                return ab;
            }
            return null;
        }
    }




}
